<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="page.queryForm" inline>
      <el-form-item label="菜单名称" prop="menu_name">
        <el-input
          v-model="page.queryForm.menu_name"
          @keyup.enter="getMenuList"
          clearable
          placeholder="请输入菜单名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input
          v-model="page.queryForm.status"
          placeholder="请输入菜单名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getMenuList"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <vxe-toolbar
      ref="toolbarRef"
      custom
      print
      :refresh="{ query: getMenuList }"
    >
      <template #buttons>
        <el-button type="primary" icon="Plus" plain @click="handleAdd()"
          >新增</el-button
        >
        <el-button type="info" icon="Sort" plain @click="handleExpand"
          >展开/折叠</el-button
        >
      </template>
    </vxe-toolbar>

    <vxe-table
      ref="menuTableRef"
      border="inner"
      align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :print-config="{}"
      :tree-config="{
        transform: true,
        rowField: 'menu_id',
        parentField: 'parent_id',
        iconOpen: 'vxe-icon-square-minus',
        iconClose: 'vxe-icon-square-plus',
      }"
      :loading="loading"
      :data="tableData"
    >
      <vxe-column field="menu_name" title="菜单名称" tree-node></vxe-column>
      <vxe-column title="图标" width="80">
        <template #default="{ row }">
          <el-icon v-if="row.icon">
            <component :is="row.icon" />
          </el-icon>
        </template>
      </vxe-column>
      <vxe-column field="order_num" title="排序" width="60"></vxe-column>
      <vxe-column field="perms" title="权限标识"></vxe-column>
      <vxe-column field="path" title="组件路径"></vxe-column>
      <vxe-column title="显示隐藏">
        <template #default="{ row }">
          <el-tag :type="row.visible === '0' ? '' : 'danger'">
            {{ row.visible === "0" ? "显示" : "隐藏" }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column title="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? '' : 'danger'">
            {{ row.status === "0" ? "正常" : "停用" }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column field="create_time" title="创建时间"></vxe-column>
      <vxe-column title="操作">
        <template #default="{ row }">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"
            >修改</el-button
          >
          <el-button link type="primary" icon="Plus" @click="handleAdd(row)"
            >新增</el-button
          >
          <el-popconfirm
            title="您确定要删除此数据吗?"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="handleDelete(row)"
          >
            <template #reference>
              <el-button link type="primary" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>

    <el-dialog
      v-model="open"
      :title="title"
      width="700px"
      append-to-body
      @closed="reset"
    >
      <el-form
        ref="formRef"
        :model="page.form"
        :rules="page.rules"
        label-width="120px"
      >
        <el-form-item label="上级菜单" prop="parent_id">
          <el-tree-select
            v-model="page.form.parent_id"
            :props="{
              value: 'menu_id',
              label: 'menu_name',
              children: 'children',
            }"
            :default-expanded-keys="['0']"
            value-key="menu_id"
            :data="menuOptions"
            check-strictly
            placeholder="请选择上级菜单"
          />
        </el-form-item>

        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menu_type">
              <el-radio-group
                v-model="page.form.menu_type"
                @change="menuTypeChange"
              >
                <!-- 这里的值在V2.6.0之前使用label 绑定,高版本可以使用value 绑定 -->
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="page.form.menu_type != 'F'">
            <el-form-item label="菜单图标" prop="icon">
              <el-input v-model="page.form.icon" placeholder="请输入菜单图标" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menu_name">
              <el-input
                v-model="page.form.menu_name"
                placeholder="请输入菜单名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="order_num">
              <el-input-number
                v-model="page.form.order_num"
                :min="0"
                :max="99"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="page.form.menu_type != 'F'">
            <el-form-item prop="is_frame">
              <template #label>
                <span>
                  <el-tooltip
                    content="选择是外链则路由地址需要以`http(s)://`开头"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  是否外链
                </span>
              </template>
              <el-radio-group v-model="page.form.is_frame">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="page.form.menu_type != 'F'">
            <el-form-item prop="path">
              <template #label>
                <span>
                  <el-tooltip
                    content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  路由地址
                </span>
              </template>
              <el-input v-model="page.form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="page.form.menu_type == 'C'">
            <el-form-item prop="component">
              <template #label>
                <span>
                  <el-tooltip
                    content="访问的组件路径，如：`system/user/index`，默认在`views`目录下"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  组件路径
                </span>
              </template>
              <el-input
                v-model="page.form.component"
                placeholder="请输入组件路径"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="page.form.menu_type != 'M'">
            <el-form-item prop="perms">
              <template #label>
                <span>
                  <el-tooltip
                    content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  权限字符
                </span>
              </template>
              <el-input v-model="page.form.perms" placeholder="请输入权限字符"/>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="page.form.menu_type == 'C'">
            <el-form-item prop="query">
              <template #label>
                <span>
                  <el-tooltip
                    content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  路由参数
                </span>
              </template>
              <el-input v-model="page.form.query" placeholder="请输入路由参数"/>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="page.form.menu_type == 'C'">
            <el-form-item prop="is_cache">
              <template #label>
                <span>
                  <el-tooltip
                    content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  是否缓存
                </span>
              </template>
              <el-radio-group v-model="page.form.is_cache">
                <el-radio :label="0">缓存</el-radio>
                <el-radio :label="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="page.form.menu_type != 'F'">
            <el-form-item prop="visible">
              <template #label>
                <span>
                  <el-tooltip
                    content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  显示状态
                </span>
              </template>
              <el-radio-group v-model="page.form.visible">
                <el-radio label="0">显示</el-radio>
                <el-radio label="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="status">
              <template #label>
                <span>
                  <el-tooltip
                    content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  菜单状态
                </span>
              </template>
              <el-radio-group v-model="page.form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  menuList,
  menuAdd,
  menuEdit,
  menuDel,
  menuInfo,
} from "@/api/system/menu.ts";

const queryFormRef = ref();
const menuTableRef = ref();
const toolbarRef = ref();
const formRef = ref();

const page = reactive({
  // query表单
  queryForm: {
    menu_name: null,
    status: null,
  },
  // 新增、修改表单数据
  form: {
    menu_id: null,
    parent_id: "0",
    menu_name: null,
    icon: null,
    menu_type: "M",
    order_num: 0,
    is_frame: 1,
    is_cache: 0,
    visible: "0",
    status: "0",
    query:null
  },
  rules: {
    menu_name: [
      { required: true, message: "菜单名称不能为空", trigger: "blur" },
    ],
    order_num: [
      { required: true, message: "菜单顺序不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
});
// 表格数据
const tableData = ref([]);
// 菜单树选项
const menuOptions = ref([]);
// 加载状态
const loading = ref(false);
// 树表格是否展开
const isExpand = ref(false);
// 新增、修改对话框的显示与隐藏
const open = ref(false);
// 对话框标题
const title = ref("");

nextTick(() => {
  // 将表格和工具栏进行关联
  const $table = menuTableRef.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
});

onMounted(() => {
  getMenuList();
});

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  getMenuList();
}

/**
 * 树表格展开/折叠事件
 */
function handleExpand() {
  isExpand.value = !isExpand.value;
  if (isExpand.value) {
    menuTableRef.value.setAllTreeExpand(true);
  } else {
    menuTableRef.value.clearTreeExpand();
  }
}

/**
 * 新增菜单
 */
function handleAdd(row = null) {
  if (row) {
    page.form.parent_id = row.menu_id;
    page.form.menu_type = row.menu_type;
  }
  getMenuTree();
  open.value = true;
  title.value = "新增菜单";
}

/**
 * 修改菜单
 * @param {Object} row 行数据
 */
function handleUpdate(row) {
  menuInfo(row.menu_id).then((res) => {
    page.form = res.data;
    nextTick(() => {
      getMenuTree();
      open.value = true;
      title.value = "修改菜单";
    });
  });
}

/**
 * 删除菜单
 * @param {Object} row 行数据
 */
function handleDelete(row) {
  menuDel(row.menu_id).then((res) => {
    getMenuList();
  });
}

/**
 * 获取菜单列表
 */
function getMenuList() {
  loading.value = true;
  menuList(page.queryForm)
    .then((res) => {
      tableData.value = res.data;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 获取菜单树
 */
function getMenuTree() {
  menuList()
    .then((res) => {
      menuOptions.value = [
        {
          menu_id: "0",
          menu_name: "主目录",
          children: listToTree(res.data, "0"),
        },
      ];
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 列表转树
 * @param {Array} list 列表
 * @param {String} parentId 父级id
 */
function listToTree(list, parentId) {
  return list
    .filter((item) => item.parent_id === parentId)
    .map((item) => ({
      ...item,
      children: listToTree(list, item.menu_id),
    }));
}

/**
 * 菜单类型改变
 * @param {*} e
 */
function menuTypeChange(e) {
  page.form.menu_type = e;
}

/**
 * 提交
 */
function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (page.form.menu_id) {
        menuEdit(page.form.menu_id, page.form).then((res) => {
          open.value = false;
          getMenuList();
        });
      } else {
        menuAdd(page.form).then((res) => {
          open.value = false;
          getMenuList();
        });
      }
    }
  });
}

/**
 * 重置
 */
function reset() {
  formRef.value.resetFields();
}
</script>

<style lang="scss" scoped></style>
